package com.tulei.admin.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.tulei.common.response.R;
import com.tulei.system.Entity.Dto.LoginDto;
import com.tulei.system.Entity.SysMenu;
import com.tulei.system.Entity.SysUser;
import com.tulei.system.Entity.vo.RouterVo;
import com.tulei.system.mapper.UserMapper;
import com.tulei.system.service.MenuService;
import com.tulei.system.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

/**
 * @Author TuLei
 * @Date 2024-06-13 13:14
 **/

@RequiredArgsConstructor
@RestController
@RequestMapping("/api")
public class SysLoginController {



    private final UserMapper userMapper;


    private final UserService userService;



    private final MenuService menuService;
    @PostMapping("/login")
    public R login(@RequestBody LoginDto login){
        return userService.login(login);
//        String username = login.getUsername();
//        String password = login.getPassword();
//        SysUser one = userMapper.selectOne(new QueryWrapper<SysUser>().eq("username", username));
//        String salt = one.getSalt();
//        String pswd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
//        if (!pswd.equals(one.getPassword())) {
//            return R.error(401,"密码错误");
//        }
//        Integer userId = one.getUserId();
//        StpUtil.login(userId);
//        StpUtil.getSession().set("user", one);
//        HashMap<String, Object> map = new HashMap<>();
//        map.put("token", StpUtil.getTokenValue());
//        return R.ok("登录成功", map);
    }


    @GetMapping("/getInfo")
    public R getInfo(){
        SysUser user = (SysUser) StpUtil.getSession().get("user");
        List<String> roles = StpUtil.getRoleList();
        List<String> perms = StpUtil.getPermissionList();
        HashMap<String, Object> map = new HashMap<>();
        map.put("roles", roles);
        map.put("perms", perms);
        map.put("user", user);
        return R.ok(map);
    }


    @GetMapping("getRouters")
    public R<List<RouterVo>> getRouters()
    {
        Long userId = (long) Integer.parseInt(StpUtil.getLoginId().toString());
        List<SysMenu> menus = menuService.selectMenuList(userId);
        return R.ok(menuService.buildMenus(menus));
    }


    @PostMapping("/logout")
    public R<Void> logout()
    {
        StpUtil.logout();
        return R.ok();
    }
}
